﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace Useful.GUI
{
    public class DataGridViewColumnCheckedHeaderCell : DataGridViewColumnHeaderCell
    {
        public event EventHandler ValueChanged = delegate {};

        private bool isChecked;
        private Rectangle cbRect = new Rectangle(0, 0, 16, 16);

        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);

            cbRect.X = 2;
            //cbRect.X = cellBounds.Width / 2 - cbRect.Width / 2;
            cbRect.Y = cellBounds.Height / 2 - cbRect.Height / 2;
            Rectangle rect = new Rectangle(new Point(cellBounds.X + cbRect.X, cellBounds.Y + cbRect.Y), cbRect.Size);

            ControlPaint.DrawCheckBox(graphics, rect, isChecked ? ButtonState.Checked : ButtonState.Normal);
        }

        public void ChangeValue()
        {
            isChecked = !isChecked;
            ValueChanged(this, EventArgs.Empty);
        }

        protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
        {
            if (cbRect.Contains(e.Location))
                ChangeValue();
            else
                base.OnMouseClick(e);
        }

        public bool IsChecked
        {
            [DebuggerStepThrough]
            get
            {
                return isChecked;
            }
            [DebuggerStepThrough]
            set
            {
                isChecked = value;
            }
        }

        public bool HitTest(MouseEventArgs e)
        {
            return cbRect.Contains(e.Location);
        }
    }
}